package com.atguigu.gulimall.product.exception;

import com.atguigu.gulimall.common.exception.BizCodeEnum;
import com.atguigu.gulimall.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestControllerAdvice
public class MyException {

    // 参数校验异常处理
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public R validExcetion(MethodArgumentNotValidException e){
        log.debug("参数校验出现异常");
        BindingResult result = e.getBindingResult();
        Map<String,String> mapError = new HashMap<>();
        result.getFieldErrors().forEach(item -> {
            mapError.put(item.getField(),item.getDefaultMessage());
        });

        System.out.println(("错误消息->mapError,{}"+mapError));

        return R.error(BizCodeEnum.VALID_EXCEPTION.getCode(),BizCodeEnum.VALID_EXCEPTION.getMessage()).put("data",mapError);
    }

    // 其他错误处理
    @ExceptionHandler(Throwable.class)
    public R OtherException(Throwable throwable){

        return R.error(BizCodeEnum.UNKNOW_EXCEPTION.getCode(),BizCodeEnum.UNKNOW_EXCEPTION.getMessage());
    }
}
